<html>
	<head>
		<title>Marbles 3D</title>
		<script type="text/javascript" src="/third-party-libs/jquery-3.1.1.min.js"></script>
		<script type="text/javascript" src="/third-party-libs/three.min.js"></script>
		<script type="text/javascript" src="/third-party-libs/jscolor.js"></script>
		<script type="text/javascript" src="/libs/FirstPersonControls.js"></script>
		<script type="text/javascript" src="/libs/MarblesViewEngine.js"></script>
		<script type="text/javascript" src="/libs/MarblesGeometry.js"></script>
		<script type="text/javascript" src="/libs/levelEditor.js"></script>
		<script type="text/javascript" src="/libs/general.js"></script>
		<link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
	  	<link type="text/css" href="/css/site.css" rel="stylesheet" />
	  	<link type="text/css" href="/css/main.css" rel="stylesheet" />
	</head>
	<body>
		<div id="scene-container" oncontextmenu="return false"></div>
		<div id="title-container" style="display: none;">
			<div class="table full tall">
				<div class="row">
					<div id="title-inner-container" class="cell">
						<h1 id="title"><i>Untitled drawing</i></h1>
						<h2>Edit: <span id="edit-url">Not saved</span></h2>
						<h2>Share: <span id="share-url">Not saved</span></h2>
					</div>
					<div id="close-title" class="cell selectable title-view" onclick="hideTitle()"><</div>
				</div>
			</div>
		</div>
		<div id="open-title-container" class="selectable title-view" style="display: none;" onclick="viewTitle()">></div>
		<div id="settings-container">
			<img id="settings" src="/images/settings.svg" border="0" class="selectable" onclick="toggleSettingsSelect();" />
			<div id="settings-menu" class="menu" style="display: none;">
				<div id="edit-details-button" onclick="editScene();" style="display: none;">Edit</div>
				<div id="save-btn" onclick="saveScene();">Save</div>
				<div id="save-btn" onclick="showControls();">Controls</div>
			</div>
		</div>
		<div id="shape-select-container" class="noselect">
			<div id="selected-shape-container" class="left" style="margin-left:3px;margin-top:3px;">
				<img id="selected-shape" src="images/cube.png" border="0" class="selectable" onclick="toggleShapeSelect()" />
			</div>
			<div class="right">
				<div class="table">
					<div class="row">
						<div class="cell" style="padding-bottom:2px;"><img id="up-arrow" src="images/up-arrow.png" border="0" class="selectable rotate-arrow" onclick="rotateUp()" /></div>
					</div>
					<div class="row">
						<div class="cell" style="padding-top:2px;"><img id="down-arrow" src="images/down-arrow.png" border="0" class="selectable rotate-arrow" onclick="rotateDown()" /></div>
					</div>
				</div>
			</div>
			<div class="clear"></div>
			<div class="table" style="margin-left:1px;margin-top:3px">
				<div class="row">
					<div class="cell left-aligned" style="padding-right:2px;"><img id="left-arrow" src="images/left-arrow.png" border="0" class="selectable rotate-arrow" onclick="rotateLeft()" /></div>
					<div class="cell right-aligned" style="padding-left:2px;"><img id="right-arrow" src="images/right-arrow.png" border="0" class="selectable rotate-arrow" onclick="rotateRight()" /></div>
				</div>
			</div>
			<div id="all-shapes" class="table menu" style="display: none;">
				<div class="row">
					<div class="cell centered"><img src="images/cube.png" border="0" class="selectable" onclick="setShape('cube')" title="Cube" /></div>
					<div class="cell centered"><img src="images/triangle.png" border="0" class="selectable" onclick="setShape('triangle')" title="Triangle" /></div>
					<div class="cell centered"><img src="images/corner.png" border="0" class="selectable" onclick="setShape('corner')" title="Corner" /></div>
					<div class="cell centered"><img src="images/pyramid.png" border="0" class="selectable" onclick="setShape('pyramid')" title="Pyramid" /></div>
				</div>
			</div>
		</div>
		<div id="color-select-container">
			<div><input type="input" id="color-select" class="jscolor selectable" onclick="document.getElementById('color-select').jscolor.show()" onchange="setColor(this.jscolor)" /></div>
			<table width="100%" cellspacing="0" cellpadding="0" style="margin-top: 5px;">
				<tr>
					<td style="width: 50%;text-align: left;">
						<table title="Opacity" cellspacing="0" cellpadding="0">
							<tr>
								<td style="padding: 2px 2px 0px 0px;"><img id="opacity-icon" src="/images/opacity.svg" /></td>
								<td><input type="text" id="opacity" value="100" /></td>
							</tr>
						</table>
					</td>
					<td style="width: 50%;text-align: right;">
						<div id="sampler-select" class="right"><img id="sampler" src="/images/dropper.svg" border="0" class="selectable" onclick="selectSampler()" title="Color Sampler" /></div>
						<div class="clear"></div>
					</td>
				</tr>
			</table>
		</div>
		<div id="loading-overlay">
    		<span></span>
			<img src="/images/loading.gif" border="0" />
		</div>
		<div id="modal-dialog-overlay" style="display: none;"></div>
		<script type="text/javascript">	
			// ----- Random numbers variables used in different areas

			var numberKeys = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"];

			// ----- Methods for the setting menu

			function toggleSettingsSelect() {
				if ($("#settings-menu").is(":visible")) hideSettingsSelect();
				else openSettingsSelect();
			}

			function openSettingsSelect() {
				$("#settings-menu").show();	
			}

			function hideSettingsSelect() {
				$("#settings-menu").hide();
			}

			function closeModalDialog() {
				$("#modal-dialog-overlay").empty();
				$("#modal-dialog-overlay").hide();

				levelEditor.setControlsEnabled(true);
			}

			// ----- Show welcome method

			function showWelcome() {
                $.ajax({
                    url: "/dialogs/welcome",
                    type: "GET",
                    success: function (response) {
						levelEditor.setControlsEnabled(false);

						$("#modal-dialog-overlay").html(response);
						$("#modal-dialog-overlay").show();

						levelEditor.setControlsEnabled(false);
                    }
                });
			}

			// ----- Saving scene method

			function saveScene() {
				hideSettingsSelect();

				if (levelEditor.getId() != null) levelEditor.save();
				else {
					levelEditor.setControlsEnabled(false);

	                $.ajax({
	                    url: "/dialogs/save",
	                    type: "GET",
	                    success: function (response) {
							$("#modal-dialog-overlay").html(response);
							$("#modal-dialog-overlay").show();
	                    }
	                });
				}
			}

			function editScene() {
				hideSettingsSelect();

				levelEditor.setControlsEnabled(false);

                $.ajax({
                    url: "/dialogs/edit",
                    type: "GET",
                    success: function (response) {
						$("#modal-dialog-overlay").html(response);

						$("#edit-scene-name").val(levelEditor.getName());

						$("#modal-dialog-overlay").show();
                    }
                });
			}

			function updateScene(name) {
				var isNewSave = levelEditor.getIsSaved();

				levelEditor.setName(name);
				levelEditor.save();

				if (isNewSave) window.history.pushState("object or string", "Saved", "/" + levelEditor.getId());

				setTitle();

				closeModalDialog();

				$("#edit-details-button").show();
				$("#settings-menu").addClass("editable");
			}

			// ----- Show controls method

			function showControls() {
				hideSettingsSelect();

                $.ajax({
                    url: "/dialogs/controls",
                    type: "GET",
                    success: function (response) {
						$("#modal-dialog-overlay").html(response);
						$("#modal-dialog-overlay").show();

						levelEditor.setControlsEnabled(false);
                    }
                });
			}

			// ----- Methods to set colors

			function selectSampler() {
				if (levelEditor.getTool() != "sampler") {
					levelEditor.setTool("sampler");
					$("#sampler-select").addClass("selected")
				}
				else {
					levelEditor.setTool("painter");
					$("#sampler-select").removeClass("selected");
				}
			}

			function setColor(color) {	
				levelEditor.setColor(color.toString());
			}

			function setOpacity() {
				if ($("#opacity").val().length > 0) {
					var opacity = 100;

					try {
						opacity = parseInt($("#opacity").val());
					}
					catch (err) {
						console.log(err);
					}

					var opacityFixed = false;

					if (opacity < 0) {
						opacity = 0;

						opacityFixed = true;
					}
					else if (opacity > 100) {
						opacity = 100;

						opacityFixed = true;
					}

					if (opacity !== 0) {

					}

					if (opacityFixed) $("#opacity").val(opacity);

					levelEditor.setOpacity(opacity);
				}
				else {
					$("#opacity").val(0);

					levelEditor.setOpacity(0);
				}
			}

			// ----- Methods for managing shapes

			function toggleShapeSelect() {
				if ($("#all-shapes").is(":visible")) hideShapeSelect();
				else openShapeSelect();
			}

			function openShapeSelect() {
				$("#all-shapes").show();	
			}

			function hideShapeSelect() {
				$("#all-shapes").hide();
			}

			function setShape(shape) {
				levelEditor.setShape(shape);

				$("#selected-shape").attr("src", "images/" + shape + ".png");

				hideShapeSelect();
			}

			// ----- Methods for rotating a shape

			function rotateLeft() {
				levelEditor.setXRotation(-90);
			}

			function rotateRight() {
				levelEditor.setXRotation(90);
			}

			function rotateUp() {
				levelEditor.setYRotation(-90);				
			}

			function rotateDown() {
				levelEditor.setYRotation(90);
			}

			// ----- Methods for title manipulation

			function viewTitle() {
				$("#title-container").show();
				$("#open-title-container").hide();
			}

			function hideTitle() {
				$("#title-container").hide();
				$("#open-title-container").show();
			}

			function setTitle() {
				document.title = levelEditor.getName();
				$("#title").html(levelEditor.getName());
				$("#edit-url").html("http://" + window.location.host + "/" + levelEditor.getId());
				$("#share-url").html("http://" + window.location.host + "/m/" + levelEditor.getShareId());
			}

			function showTitle() {
				$("#title-container").show();
			}

			// ----- Event binding

			// Trying to stop events getting passed onto the editor

			document.getElementById("title-container").addEventListener('mousedown', function(e) {
				e.stopPropagation();
			}, false);

			document.getElementById("open-title-container").addEventListener('mousedown', function(e) {
				e.stopPropagation();
			}, false);

			document.getElementById("settings-container").addEventListener('mousedown', function(e) {
				e.stopPropagation();
			}, false);

			document.getElementById("shape-select-container").addEventListener('mousedown', function(e) {
				e.stopPropagation();
			}, false);

			document.getElementById("color-select-container").addEventListener('mousedown', function(e) {
				e.stopPropagation();
			}, false);

			document.getElementById("color-select-container").addEventListener('keydown', function(e) {
				e.stopPropagation();
			}, false);

			document.getElementById("color-select-container").addEventListener('keydown', function(e) {
				e.stopPropagation();
			}, false);

			// Event listeners to help control the block opacity

			document.getElementById("opacity").addEventListener('mousedown', function(e) {
				e.stopPropagation();
			}, false);

			document.getElementById("opacity").addEventListener('mousemove', function(e) {
				e.stopPropagation();
			}, false);

			document.getElementById("opacity").addEventListener('keydown', function(e) {

				if ((numberKeys.indexOf(e.key) === -1) && 
					((e.keyCode !== 8) && (e.keyCode !== 46) && (e.keyCode !== 37) && (e.keyCode !== 39) && (e.keyCode !== 13))) {
					e.preventDefault();
				}
				else if (e.keyCode === 13) {
					$("#opacity").blur();
				}
			}, false);

			document.getElementById("opacity").addEventListener('blur', function(e) {
				setOpacity();
			}, false);

			// Other control methods

			$(".rotate-arrow").mousedown(function(e) {
				$(this).attr("src", "images/" + $(this).attr("id") + "-selected.png");
			});

			$(".rotate-arrow").mouseup(function(e) {
				$(this).attr("src", "images/" + $(this).attr("id") + ".png");
			});

			document.addEventListener("mouseout", function() {
				levelEditor.cancelMovement();
			}, false);

			document.addEventListener("mousedown", function(e) {
				$("#color-select").blur();
				$("#opacity").blur();
			}, false);

			document.addEventListener('keydown', function(e) {
				e.stopPropagation();

				var keyCode = e.code.toLowerCase();

				var isGridCommand = false;

				if (keyCode == "arrowup") {
					levelEditor.setLevelUpSelected(true);
					isGridCommand = true;
				}
				else if (keyCode == "arrowdown") {
					levelEditor.setLevelDownSelected(true);
					isGridCommand = true;
				}

				if (isGridCommand) e.preventDefault();
			});

			document.addEventListener('keyup', function(e) {
				e.stopPropagation();

				var keyCode = e.code.toLowerCase();

				var isGridCommand = false;

				if (keyCode == "arrowup") {
					levelEditor.setLevelUpSelected(false);
					isGridCommand = true;
				}
				else if (keyCode == "arrowdown") {
					levelEditor.setLevelDownSelected(false);
					isGridCommand = true;
				}
				else if (keyCode == "arrowleft") {
					levelEditor.rotateGridLeft();
					isGridCommand = true;
				}
				else if (keyCode == "arrowright") {
					levelEditor.rotateGridRight();
					isGridCommand = true;
				}

				if (isGridCommand) e.preventDefault();

				if (e.keyCode == 13) {
					$("#color-select").blur();
					document.getElementById('color-select').jscolor.hide();
				}
			}, false);


			document.addEventListener("mousewheel", MouseWheelHandler, false);
			document.addEventListener("DOMMouseScroll", MouseWheelHandler, false);

			function MouseWheelHandler(e) {
				e.stopPropagation();
				e.preventDefault();

				if (e.deltaY) {
					var level = levelEditor.getLevel();

					if (e.deltaY < 0) levelEditor.moveLevelUp();
					else levelEditor.moveLevelDown();
				}
			}

			var startColor = "#ff0000";

			$("#color-select").val(startColor);

			var levelEditor = new LevelEditor();

			levelEditor.start("scene-container", startColor);

			levelEditor.setEventManager(function(action, details) {
				if (action == "toolChange") {
					if ((details != null) && (details.from != null)) {
						if (details.from == "sampler") {
							// Set the color selector to the sampled color
							document.getElementById('color-select').jscolor.fromString(levelEditor.getColor());
							$("#sampler-select").removeClass("selected");

							// Set the opacity to the sampled opacity
							$("#opacity").val(levelEditor.getOpacity());
						}
					}
				}
			});
			
			levelEditor.onError = function(message) {
                $.ajax({
                    url: "/dialogs/error",
                    type: "GET",
                    success: function (response) {
						$("#modal-dialog-overlay").html(response);

						$("#error-message").html(message);

						$("#modal-dialog-overlay").show();
                    }
                });
			};

			levelEditor.onLoad = function(loaded) { 
				if (loaded) {
					$("#edit-details-button").show();
					$("#settings-menu").addClass("editable");

					setTitle();
				}

				showTitle();
					
				$("#loading-overlay").hide();
			};

			var sceneId = getURLParam("id");
			if (sceneId != null) {
				levelEditor.load(sceneId);
			}
			else {
				showWelcome();
				
				$("#loading-overlay").hide();

				showTitle();
			}
		</script>
	</body>
</html>